<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
<script>

	// UC API 示例 JS 语言（泄露 Secret 不推荐使用）

	class Request {
		constructor() {
			this.url = 'http://127.0.0.1/uc_core/upload/api/';
			this.appid = '14664096';
			this.secret = 'E9JOFOFEQQSSZFLE';
			this.token = '';
		}

		async sample() {
			try {
				let ret = await this._request('/token', {});
				if (!ret || ret.ret > 0 || !ret.token) {
					throw new Error('接口错误，无法获取 Token');
				}
				this.token = ret.token;

				ret = await this._request('/user/login', {
					username: 'test',
					password: '1',
				});
				if (!ret || ret.ret > 0) {
					throw new Error('接口错误，无法获取 /user/login');
				}
				console.log(ret);

				ret = await this._request('/user/get_user', {
					username: 'admin',
				});
				console.log(ret);
			} catch (error) {
				console.error(error.message);
			}
		}

		async _request(uri, post) {
			const nonce = Math.floor(Math.random() * 1000) + 1000;
			const t = Math.floor(Date.now() / 1000);
			const sign = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(CryptoJS.SHA256(nonce.toString() + t.toString() + this.secret).toString()));

			const headers = {
				'appid': this.appid,
				'nonce': nonce.toString(),
				't': t.toString(),
				'sign': await sign,
			};

			if (this.token) {
				headers['token'] = this.token;
			}

			const response = await fetch(this.url + '?' + uri, {
				method: 'POST',
				headers: headers,
				body: JSON.stringify(post),
			});

			if (!response.ok) {
				throw new Error('Network response was not ok');
			}

			const data = await response.json();
			console.log(data);
			return data;
		}
	}

	// 使用示例
	const r = new Request();
	r.sample();
</script>